package com.doubao.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.user.service.TokenService;
import com.doubao.common.result.Result;
import com.doubao.user.entity.MembershipLevel;
import com.doubao.user.entity.MembershipOperationLog;
import com.doubao.user.entity.User;
import com.doubao.user.entity.UserMembership;
import com.doubao.user.dto.MembershipDTO;
import com.doubao.user.mapper.MembershipLevelMapper;
import com.doubao.user.mapper.MembershipOperationLogMapper;
import com.doubao.user.mapper.UserMapper;
import com.doubao.user.mapper.UserMembershipMapper;
import com.doubao.user.service.MembershipService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 会员服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MembershipServiceImpl extends ServiceImpl<UserMembershipMapper, UserMembership> implements MembershipService {

    private final UserMembershipMapper userMembershipMapper;
    private final MembershipLevelMapper membershipLevelMapper;
    private final MembershipOperationLogMapper operationLogMapper;
    private final UserMapper userMapper;
    private final TokenService tokenService;

    @Override
    public Result<List<MembershipLevel>> getAllLevels() {
        LambdaQueryWrapper<MembershipLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MembershipLevel::getStatus, 1)
                .orderByAsc(MembershipLevel::getId);

        List<MembershipLevel> levels = membershipLevelMapper.selectList(wrapper);
        return Result.success(levels);
    }

    @Override
    public Result<MembershipLevel> getLevelById(Integer levelId) {
        MembershipLevel level = membershipLevelMapper.selectById(levelId);
        if (level == null || level.getStatus() != 1) {
            return Result.failed("会员等级不存在或已禁用");
        }
        return Result.success(level);
    }

    @Override
    public Result<MembershipDTO> getUserMembership(Long userId) {
        if (userId == null) {
            return Result.failed("用户ID不能为空");
        }

        // 获取用户当前有效的会员信息
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果没有会员信息，返回默认的免费用户权益
            MembershipLevel freeLevel = getFreeMembershipLevel();
            if (freeLevel == null) {
                return Result.failed("系统错误：找不到免费用户权益配置");
            }

            MembershipDTO dto = new MembershipDTO();
            dto.setUserId(userId);
            dto.setIsVip(false);
            dto.setLevelId(freeLevel.getId());
            dto.setLevelName(freeLevel.getName());
            dto.setLevelCode(freeLevel.getCode());
            dto.setDailyTokenLimit(freeLevel.getDailyTokenLimit());
            dto.setChatLimit(freeLevel.getChatLimit());
            dto.setSwitchAgentLimit(freeLevel.getSwitchAgentLimit());
            dto.setExpireTime(null);
            dto.setRemainingChatCount(freeLevel.getChatLimit());
            dto.setRemainingSwitchCount(freeLevel.getSwitchAgentLimit());

            return Result.success(dto);
        }

        // 获取会员等级信息
        MembershipLevel level = membershipLevelMapper.selectById(membership.getLevelId());
        if (level == null) {
            return Result.failed("会员等级配置不存在");
        }

        // 构建返回DTO
        MembershipDTO dto = new MembershipDTO();
        dto.setUserId(userId);
        dto.setIsVip(true);
        dto.setLevelId(level.getId());
        dto.setLevelName(level.getName());
        dto.setLevelCode(level.getCode());
        dto.setDailyTokenLimit(level.getDailyTokenLimit());
        dto.setChatLimit(level.getChatLimit());
        dto.setSwitchAgentLimit(level.getSwitchAgentLimit());
        dto.setExpireTime(membership.getExpireTime());
        dto.setSubscriptionType(membership.getSubscriptionType());
        dto.setRemainingChatCount(membership.getRemainingChatCount());
        dto.setRemainingSwitchCount(membership.getRemainingSwitchCount());
        dto.setMembershipId(membership.getId());

        return Result.success(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> createMembership(Long userId, Integer levelId, String subscriptionType,
                                         Integer days, String source, String orderId) {
        if (userId == null || levelId == null || subscriptionType == null || days == null || days <= 0) {
            log.warn("【会员创建】参数错误: userId={}, levelId={}, subscriptionType={}, days={}", 
                    userId, levelId, subscriptionType, days);
            return Result.failed("参数错误");
        }

        // 检查用户是否存在
        log.info("【会员创建】开始创建会员: userId={}, levelId={}, subscriptionType={}, days={}, source={}, orderId={}",
                userId, levelId, subscriptionType, days, source, orderId);
        
        User user = userMapper.selectById(userId);
        if (user == null) {
            log.error("【会员创建】用户不存在: userId={}", userId);
            return Result.failed("用户不存在");
        }
        log.info("【会员创建】获取到用户信息: userId={}, nickname={}", userId, user.getNickname());

        // 检查会员等级是否存在
        MembershipLevel level = membershipLevelMapper.selectById(levelId);
        if (level == null || level.getStatus() != 1) {
            log.error("【会员创建】会员等级不存在或已禁用: levelId={}", levelId);
            return Result.failed("会员等级不存在或已禁用");
        }
        log.info("【会员创建】获取到会员等级信息: levelId={}, name={}, code={}", 
                levelId, level.getName(), level.getCode());

        // 检查用户是否已经有会员
        log.info("【会员创建】检查用户是否已经有有效会员: userId={}", userId);
        UserMembership existingMembership = getCurrentMembership(userId);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expireTime = now.plusDays(days);
        
        if (existingMembership != null) {
            log.info("【会员创建】用户已有会员记录: id={}, levelId={}, 当前等级={}, 到期时间={}", 
                    existingMembership.getId(), existingMembership.getLevelId(), 
                    level.getName(), existingMembership.getExpireTime());
            
            // 如果是同一等级
            if (existingMembership.getLevelId().equals(levelId)) {
                log.info("【会员创建】相同等级会员，延长有效期");
                // 如果当前会员未过期，在现有基础上延长
                if (existingMembership.getExpireTime().isAfter(now)) {
                    expireTime = existingMembership.getExpireTime().plusDays(days);
                    log.info("【会员创建】在现有到期时间基础上延长: 原到期时间={}, 新到期时间={}", 
                            existingMembership.getExpireTime(), expireTime);
                }
            } else {
                // 如果是升级到更高等级
                log.info("【会员创建】会员等级变更: 原等级ID={}, 新等级ID={}", 
                        existingMembership.getLevelId(), levelId);
            }
            
            // 更新现有会员信息
            existingMembership.setLevelId(levelId);
            existingMembership.setSubscriptionType(subscriptionType);
            existingMembership.setExpireTime(expireTime);
            existingMembership.setStatus(1);
            existingMembership.setTokenRefreshDate(LocalDate.now());
            existingMembership.setRemainingChatCount(level.getChatLimit());
            existingMembership.setRemainingSwitchCount(level.getSwitchAgentLimit());
            existingMembership.setSource(source);
            existingMembership.setOrderId(orderId);
            existingMembership.setUpdatedAt(now);
            
            userMembershipMapper.updateById(existingMembership);
            log.info("【会员创建】更新现有会员记录: id={}, 等级={}, 新到期时间={}", 
                    existingMembership.getId(), level.getName(), expireTime);
            
            // 记录操作日志
            log.info("【会员创建】记录会员操作日志: 类型=续期, 用户={}, 等级={}", userId, level.getName());
            MembershipOperationLog operationLog = new MembershipOperationLog();
            operationLog.setUserId(userId);
            operationLog.setMembershipId(existingMembership.getId());
            operationLog.setOperationType("RENEW");
            operationLog.setLevelId(levelId);
            operationLog.setOperationDesc("续订" + level.getName() + "，有效期" + days + "天");
            operationLog.setNewValue(subscriptionType + "," + expireTime);
            operationLog.setCreatedAt(now);
            operationLogMapper.insert(operationLog);
            
        } else {
            // 创建新会员
            log.info("【会员创建】创建新会员记录: userId={}, levelId={}, expireTime={}", 
                    userId, levelId, expireTime);
            
            UserMembership membership = new UserMembership();
            membership.setUserId(userId);
            membership.setLevelId(levelId);
            membership.setSubscriptionType(subscriptionType);
            membership.setStartTime(now);
            membership.setExpireTime(expireTime);
            membership.setStatus(1);
            membership.setTokenRefreshDate(LocalDate.now());
            membership.setRemainingChatCount(level.getChatLimit());
            membership.setRemainingSwitchCount(level.getSwitchAgentLimit());
            membership.setSource(source);
            membership.setOrderId(orderId);
            membership.setCreatedAt(now);
            membership.setUpdatedAt(now);
            
            userMembershipMapper.insert(membership);
            log.info("【会员创建】新会员记录创建成功: id={}, userId={}, expireTime={}", 
                    membership.getId(), userId, expireTime);
            
            // 记录操作日志
            log.info("【会员创建】记录会员操作日志: 类型=购买, 用户={}, 等级={}", userId, level.getName());
            MembershipOperationLog operationLog = new MembershipOperationLog();
            operationLog.setUserId(userId);
            operationLog.setMembershipId(membership.getId());
            operationLog.setOperationType("PURCHASE");
            operationLog.setLevelId(levelId);
            operationLog.setOperationDesc("购买" + level.getName() + "，有效期" + days + "天");
            operationLog.setNewValue(subscriptionType + "," + expireTime);
            operationLog.setCreatedAt(now);
            operationLogMapper.insert(operationLog);
        }

        // 更新用户VIP状态
        log.info("【会员创建】更新用户VIP状态: userId={}, 设置为VIP", userId);
        user.setVipStatus(1);
        userMapper.updateById(user);

        // 刷新会员token
        log.info("【会员创建】刷新会员token额度: userId={}", userId);
        Result<Void> refreshResult = refreshDailyTokens(userId);
        if (!refreshResult.isSuccess()) {
            log.warn("【会员创建】刷新token额度失败: {}", refreshResult.getMessage());
        } else {
            log.info("【会员创建】刷新token额度成功");
        }

        // 如果是临时卡（2元卡），直接充值token并增加聊天次数和智能体切换次数
        if ("TEMP".equals(level.getCode())) {
            log.info("【会员创建】检测到临时卡(2元卡)会员: userId={}, 准备执行额外充值", userId);
            
            // 充值token
            log.info("【会员创建】为临时卡会员充值token: userId={}, 数量={}", userId, level.getDailyTokenLimit());
            tokenService.rechargeTokens(userId, level.getDailyTokenLimit());

            // 获取当前会员信息以更新聊天次数和智能体切换次数
            UserMembership updatedMembership = getCurrentMembership(userId);
            if (updatedMembership != null) {
                // 增加100次聊天次数
                int newChatCount = updatedMembership.getRemainingChatCount() + 100;
                // 增加10次智能体切换次数
                int newSwitchCount = updatedMembership.getRemainingSwitchCount() + 10;
                
                log.info("【会员创建】增加临时卡会员额外权益: userId={}, 聊天次数+100={}, 切换次数+10={}", 
                        userId, newChatCount, newSwitchCount);
                
                updatedMembership.setRemainingChatCount(newChatCount);
                updatedMembership.setRemainingSwitchCount(newSwitchCount);
                // 更新会员信息
                userMembershipMapper.updateById(updatedMembership);
                log.info("【会员创建】临时卡会员权益更新完成");

                // 记录操作日志
                log.info("【会员创建】记录临时卡额外充值操作日志");
                MembershipOperationLog tempCardLog = new MembershipOperationLog();
                tempCardLog.setUserId(userId);
                tempCardLog.setMembershipId(updatedMembership.getId());
                tempCardLog.setOperationType("RECHARGE");
                tempCardLog.setLevelId(updatedMembership.getLevelId());
                tempCardLog.setOperationDesc("临时卡充值：增加100次聊天和10次智能体切换");
                tempCardLog.setNewValue("chat:+100,switch:+10");
                tempCardLog.setCreatedAt(LocalDateTime.now());
                operationLogMapper.insert(tempCardLog);

                log.info("【会员创建】用户[{}]临时卡充值：增加100次聊天和10次智能体切换", userId);
            } else {
                log.warn("【会员创建】无法获取更新后的临时卡会员信息, userId={}", userId);
            }
        }

        log.info("【会员创建】会员创建完成: userId={}, levelId={}, 等级名称={}, 有效期至={}", 
                userId, levelId, level.getName(), expireTime);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateMembershipLevel(Long userId, Integer levelId, String subscriptionType,
                                              Integer days, String source) {
        if (userId == null || levelId == null || days == null || days <= 0) {
            return Result.failed("参数错误");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        // 检查会员等级是否存在
        MembershipLevel level = membershipLevelMapper.selectById(levelId);
        if (level == null || level.getStatus() != 1) {
            return Result.failed("会员等级不存在或已禁用");
        }

        // 获取用户当前会员
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果没有会员记录，创建一个新的
            return createMembership(userId, levelId, subscriptionType, days, source, null);
        }

        // 保存旧值
        Integer oldLevelId = membership.getLevelId();
        LocalDateTime oldExpireTime = membership.getExpireTime();

        // 设置新的会员等级和有效期
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime newExpireTime;

        // 如果当前会员未过期，在现有基础上延长
        if (oldExpireTime.isAfter(now)) {
            newExpireTime = oldExpireTime.plusDays(days);
        } else {
            // 如果已过期，从当前时间开始计算
            newExpireTime = now.plusDays(days);
        }

        // 更新会员信息
        membership.setLevelId(levelId);
        membership.setSubscriptionType(subscriptionType);
        membership.setExpireTime(newExpireTime);
        membership.setStatus(1);
        // 重置每日限额
        membership.setRemainingChatCount(level.getChatLimit());
        membership.setRemainingSwitchCount(level.getSwitchAgentLimit());
        membership.setUpdatedAt(now);

        userMembershipMapper.updateById(membership);

        // 记录操作日志
        MembershipOperationLog log = new MembershipOperationLog();
        log.setUserId(userId);
        log.setMembershipId(membership.getId());
        log.setOperationType("UPGRADE");
        log.setLevelId(levelId);
        log.setOperationDesc("升级会员从" + oldLevelId + "到" + levelId);
        log.setOldValue(oldLevelId + "," + oldExpireTime);
        log.setNewValue(levelId + "," + newExpireTime);
        log.setCreatedAt(now);
        operationLogMapper.insert(log);

        // 确保用户VIP状态正确
        if (user.getVipStatus() != 1) {
            user.setVipStatus(1);
            userMapper.updateById(user);
        }

        // 刷新会员token
        refreshDailyTokens(userId);

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> renewMembership(Long userId, Integer days, String source, String orderId) {
        if (userId == null || days == null || days <= 0) {
            return Result.failed("参数错误");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        // 获取用户当前会员
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            return Result.failed("用户没有会员");
        }

        // 获取会员等级
        MembershipLevel level = membershipLevelMapper.selectById(membership.getLevelId());
        if (level == null) {
            return Result.failed("会员等级不存在");
        }

        // 保存旧值
        LocalDateTime oldExpireTime = membership.getExpireTime();

        // 计算新的过期时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime newExpireTime;

        // 如果当前会员未过期，在现有基础上延长
        if (oldExpireTime.isAfter(now)) {
            newExpireTime = oldExpireTime.plusDays(days);
        } else {
            // 如果已过期，从当前时间开始计算
            newExpireTime = now.plusDays(days);
        }

        // 更新会员信息
        membership.setExpireTime(newExpireTime);
        membership.setStatus(1);
        membership.setOrderId(orderId);
        membership.setUpdatedAt(now);

        userMembershipMapper.updateById(membership);

        // 记录操作日志
        MembershipOperationLog log = new MembershipOperationLog();
        log.setUserId(userId);
        log.setMembershipId(membership.getId());
        log.setOperationType("RENEW");
        log.setLevelId(membership.getLevelId());
        log.setOperationDesc("续费" + level.getName() + "，延长" + days + "天");
        log.setOldValue(oldExpireTime.toString());
        log.setNewValue(newExpireTime.toString());
        log.setCreatedAt(now);
        operationLogMapper.insert(log);

        // 确保用户VIP状态正确
        if (user.getVipStatus() != 1) {
            user.setVipStatus(1);
            userMapper.updateById(user);
        }

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> refreshDailyTokens(Long userId) {
        if (userId == null) {
            return Result.failed("用户ID不能为空");
        }

        LocalDate today = LocalDate.now();

        // 获取用户会员信息
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果不是会员，使用普通用户限额
            MembershipLevel freeLevel = getFreeMembershipLevel();
            if (freeLevel == null) {
                log.error("找不到免费用户权益配置");
                return Result.failed("系统错误");
            }

            // 非会员直接更新用户token余额为100
            User user = userMapper.selectById(userId);
            if (user == null) {
                return Result.failed("用户不存在");
            }

            user.setTotalTokensBalance(100);
            userMapper.updateById(user);

            // 记录操作日志
            MembershipOperationLog log = new MembershipOperationLog();
            log.setUserId(userId);
            log.setOperationType("TOKEN_REFRESH");
            log.setOperationDesc("普通用户每日token刷新");
            log.setNewValue("token:100");
            log.setCreatedAt(LocalDateTime.now());
            operationLogMapper.insert(log);

            return Result.success();
        }

        // 检查是否已经刷新过
        if (membership.getTokenRefreshDate() != null && membership.getTokenRefreshDate().equals(today)) {
            // 今天已经刷新过了
            return Result.success();
        }

        // 获取会员等级
        MembershipLevel level = membershipLevelMapper.selectById(membership.getLevelId());
        if (level == null) {
            log.error("找不到会员等级：{}", membership.getLevelId());
            return Result.failed("会员等级配置错误");
        }

        // 更新用户token余额
        // 这里可以考虑保留原来的余额，也可以直接设置为会员等级的每日限额
        // 这里选择刷新为会员等级的每日限额
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        // 更新用户token余额
        user.setTotalTokensBalance(level.getDailyTokenLimit());
        userMapper.updateById(user);

        // 更新会员信息
        membership.setTokenRefreshDate(today);
        membership.setRemainingChatCount(level.getChatLimit());
        membership.setRemainingSwitchCount(level.getSwitchAgentLimit());
        membership.setUpdatedAt(LocalDateTime.now());
        userMembershipMapper.updateById(membership);

        // 记录操作日志
        MembershipOperationLog log = new MembershipOperationLog();
        log.setUserId(userId);
        log.setMembershipId(membership.getId());
        log.setOperationType("REFRESH");
        log.setLevelId(membership.getLevelId());
        log.setOperationDesc("刷新每日权益");
        log.setNewValue("token:" + level.getDailyTokenLimit() + ",chat:" + level.getChatLimit() + ",switch:" + level.getSwitchAgentLimit());
        log.setCreatedAt(LocalDateTime.now());
        operationLogMapper.insert(log);

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> consumeChatCount(Long userId) {
        if (userId == null) {
            return Result.failed("用户ID不能为空");
        }

        // 获取用户会员信息
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果不是会员，使用普通用户限额
            MembershipLevel freeLevel = getFreeMembershipLevel();
            if (freeLevel == null) {
                log.error("找不到免费用户权益配置");
                return Result.failed("系统错误");
            }

            // 检查免费用户今日是否有聊天次数
            if (!hasSufficientChatCount(userId)) {
                return Result.failed("今日聊天次数已用完");
            }

            // TODO: 为非会员用户创建临时记录以跟踪聊天次数
            // 目前简单返回成功
            return Result.success();
        }

        // 检查剩余聊天次数
        if (membership.getRemainingChatCount() <= 0) {
            return Result.failed("今日聊天次数已用完");
        }

        // 扣减聊天次数
        membership.setRemainingChatCount(membership.getRemainingChatCount() - 1);
        membership.setUpdatedAt(LocalDateTime.now());
        userMembershipMapper.updateById(membership);

        // 记录操作日志
        MembershipOperationLog log = new MembershipOperationLog();
        log.setUserId(userId);
        log.setMembershipId(membership.getId());
        log.setOperationType("CONSUME");
        log.setLevelId(membership.getLevelId());
        log.setOperationDesc("消费聊天次数");
        log.setOldValue(String.valueOf(membership.getRemainingChatCount() + 1));
        log.setNewValue(String.valueOf(membership.getRemainingChatCount()));
        log.setCreatedAt(LocalDateTime.now());
        operationLogMapper.insert(log);

        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> consumeSwitchCount(Long userId) {
        if (userId == null) {
            return Result.failed("用户ID不能为空");
        }

        // 只检查用户是否是会员，不再依赖 SmartDevice
        boolean isVip = isVipMember(userId);
        if (!isVip) {
            return Result.failed("该智能体需要会员才能使用，请先开通会员");
        }

        // 如果是会员，直接返回成功
        return Result.success();
    }

    @Override
    public boolean isVipMember(Long userId) {
        if (userId == null) {
            return false;
        }

        UserMembership membership = getCurrentMembership(userId);
        return membership != null;
    }

    @Override
    public boolean hasSufficientChatCount(Long userId) {
        if (userId == null) {
            return false;
        }

        // 获取用户会员信息
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果不是会员，检查免费用户限额
            MembershipLevel freeLevel = getFreeMembershipLevel();
            if (freeLevel == null) {
                log.error("找不到免费用户权益配置");
                return false;
            }

            // 检查今日已使用聊天次数
            // TODO: 实现非会员用户聊天次数跟踪
            // 对于非会员，简单检查token余额是否足够
            return tokenService.hasEnoughTokensForMessage(userId);
        }

        // 检查会员剩余聊天次数
        return membership.getRemainingChatCount() > 0;
    }

    @Override
    public boolean hasSufficientSwitchCount(Long userId) {
        if (userId == null) {
            return false;
        }

        // 获取用户会员信息
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果不是会员，检查免费用户限额
            MembershipLevel freeLevel = getFreeMembershipLevel();
            if (freeLevel == null) {
                log.error("找不到免费用户权益配置");
                return false;
            }

            // 检查今日已使用切换次数
            // TODO: 实现非会员用户切换次数跟踪
            // 对于非会员，简单检查token余额是否足够
            return tokenService.hasEnoughTokens(userId, 50);
        }

        // 检查会员剩余切换次数
        return membership.getRemainingSwitchCount() > 0;
    }

    @Override
    public int getRemainingChatCount(Long userId) {
        if (userId == null) {
            return 0;
        }

        // 获取用户会员信息
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果不是会员，使用普通用户限额
            MembershipLevel freeLevel = getFreeMembershipLevel();
            if (freeLevel == null) {
                log.error("找不到免费用户权益配置");
                return 0;
            }

            // TODO: 跟踪非会员用户的聊天使用情况
            // 目前简单返回免费用户最大限额
            return freeLevel.getChatLimit();
        }

        return membership.getRemainingChatCount();
    }

    @Override
    public int getRemainingSwitchCount(Long userId) {
        if (userId == null) {
            return 0;
        }

        // 获取用户会员信息
        UserMembership membership = getCurrentMembership(userId);
        if (membership == null) {
            // 如果不是会员，使用普通用户限额
            MembershipLevel freeLevel = getFreeMembershipLevel();
            if (freeLevel == null) {
                log.error("找不到免费用户权益配置");
                return 0;
            }

            // TODO: 跟踪非会员用户的切换使用情况
            // 目前简单返回免费用户最大限额
            return freeLevel.getSwitchAgentLimit();
        }

        return membership.getRemainingSwitchCount();
    }

    /**
     * 获取用户当前有效的会员信息
     */
    private UserMembership getCurrentMembership(Long userId) {
        LambdaQueryWrapper<UserMembership> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMembership::getUserId, userId)
                .eq(UserMembership::getStatus, 1)
                .ge(UserMembership::getExpireTime, LocalDateTime.now())
                .orderByDesc(UserMembership::getExpireTime)
                .last("LIMIT 1");

        return userMembershipMapper.selectOne(wrapper);
    }

    /**
     * 获取免费用户等级
     */
    private MembershipLevel getFreeMembershipLevel() {
        LambdaQueryWrapper<MembershipLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MembershipLevel::getCode, "FREE")
                .eq(MembershipLevel::getStatus, 1);

        return membershipLevelMapper.selectOne(wrapper);
    }
}